package utils;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.Before;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.*;

public class HikariCPJDBCUtils {
    private static HikariDataSource ds;

    @Before
    public void init(){
        HikariConfig config = new HikariConfig("src/test/resources/hikariCP.properties");
        ds = new HikariDataSource(config);
    }

    @Test
    public void hikariCPTest(){
        Connection conn = null;
        PreparedStatement pstmt = null;
        /**
         * 添加数据
         */
        try{
            conn = getConnection();
            String sql = "insert into points values (?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,"001");
            pstmt.setString(2,"HikariCP");
            pstmt.setInt(3,500);
            int i = pstmt.executeUpdate();
            System.out.println(i);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close(pstmt,conn);
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 释放资源
     */
    public static void close(Statement stmt, Connection conn){
        close(null,stmt,conn);
    }

    public static void close(ResultSet set, Statement stmt, Connection conn){
        if(set!=null){
            try {
                set.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn!=null){
            try {
                conn.close();//归还资源
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取连接池
     */
    public static DataSource getDatasource(){
        return ds;
    }
}
